package com.mit.facade;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.mit.common.RequestContext;
import com.mit.common.ResultContext;
import com.mit.common.exception.BaseException;
import com.mit.common.exception.DuplicateKeyException;
import com.mit.common.exception.NoRecordUpdateException;
import com.mit.common.purchase.dto.ColorStyleDTO;
import com.mit.common.purchase.dto.InquiryItemDTO;
import com.mit.common.purchase.dto.InquiryTaskDTO;
import com.mit.common.purchase.dto.MaterialDTO;
import com.mit.common.purchase.dto.SupplierDTO;
import com.mit.common.security.dto.UserDTO;
import com.mit.common.token.DesignTokens;
import com.mit.common.token.PurchaseTokens;
import com.mit.common.token.Tokens;
import com.mit.service.core.dao.ISequenceDAO;
import com.mit.service.purchase.dao.IColorStyleDAO;
import com.mit.service.purchase.dao.IInquiryItemDAO;
import com.mit.service.purchase.dao.IInquiryTaskDAO;
import com.mit.service.purchase.dao.IMaterialDAO;
import com.mit.service.purchase.dao.ISupplierDAO;

public class PurchaseFacade implements IPurchaseFacade {

	private Logger logger = Logger.getLogger(PurchaseFacade.class);
	
	private ISequenceDAO sequenceDAO;
	private ISupplierDAO supplierDAO;
	private IMaterialDAO materialDAO;
	private IColorStyleDAO colorStyleDAO;
	private IInquiryTaskDAO inquiryTaskDAO;
	private IInquiryItemDAO inquiryItemDAO;
	
	
	
	public void setInquiryTaskDAO(IInquiryTaskDAO inquiryTaskDAO) {
		this.inquiryTaskDAO = inquiryTaskDAO;
	}
	public void setInquiryItemDAO(IInquiryItemDAO inquiryItemDAO) {
		this.inquiryItemDAO = inquiryItemDAO;
	}
	public void setMaterialDAO(IMaterialDAO materialDAO) {
		this.materialDAO = materialDAO;
	}
	public void setColorStyleDAO(IColorStyleDAO colorStyleDAO) {
		this.colorStyleDAO = colorStyleDAO;
	}
	public void setSequenceDAO(ISequenceDAO sequenceDAO) {
		this.sequenceDAO = sequenceDAO;
	}
	public void setSupplierDAO(ISupplierDAO supplierDAO) {
		this.supplierDAO = supplierDAO;
	}
	
	@Override
	public ResultContext saveSupplier(RequestContext rqs)
			throws BaseException {
		SupplierDTO supplier = (SupplierDTO) rqs.getParameter(PurchaseTokens.KEY_SUPPLIER_DTO);
		UserDTO user = rqs.getUser();
		supplier.setOrgId(user.getOrgId());
		
		if(supplier.getId() < 1){
			logger.debug("new supplier");
			//验证：简称不能重复
			if(supplierDAO.hasSupplier(user.getOrgId(), null, supplier.getName())){
				logger.error("Duplicate Name: " + supplier.getName());
				throw new DuplicateKeyException(supplier.getName());
			}
			supplier = supplierDAO.createSupplierDTO(supplier);
			logger.info("new supplier created: " + supplier.getName());
		}else{
			logger.debug("update supplier");
			//验证：简称不能重复
			if(supplierDAO.hasSupplier(user.getOrgId(),supplier.getId(), supplier.getName())){
				logger.error("Duplicate Name: " + supplier.getName());
				throw new DuplicateKeyException(supplier.getName());
			}
			supplierDAO.updateSupplierDTO(supplier);
			logger.info("supplier updated: " + supplier.getName());
		}
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_SUPPLIER_DTO, supplier);
		return rlt;
	}

	@Override
	public ResultContext retrievePagedSuppliers(RequestContext rqs) {
		UserDTO user = rqs.getUser();
		String key = (String) rqs.getParameter(PurchaseTokens.KEY_SUPPLIER_NAME);
		Integer pageNo = (Integer) rqs.getParameter(Tokens.KEY_PAGE_NO);
		Integer pageSize = (Integer) rqs.getParameter(Tokens.KEY_PAGE_SIZE);
		List<SupplierDTO> lst = supplierDAO.retrievePagedSuppliers(user.getOrgId(), key, pageNo, pageSize);
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_SUPPLIER_LIST, lst);
		return rlt;
	}

	@Override
	public ResultContext retrieveSupplierCount(RequestContext rqs) {
		UserDTO user = rqs.getUser();
		String key = (String) rqs.getParameter(PurchaseTokens.KEY_SUPPLIER_NAME);
		Integer rowCount = supplierDAO.retrieveSuppliersCount(user.getOrgId(),key);
		ResultContext rlt = new ResultContext();
		rlt.addResult(Tokens.KEY_RECORD_COUNT, rowCount);
		return rlt;
	}

	@Override
	public ResultContext retrieveSuppliersBasicInfo(RequestContext rqs) {
		UserDTO user = rqs.getUser();
		String name = (String) rqs.getParameter(PurchaseTokens.KEY_SUPPLIER_NAME);
		List<SupplierDTO> lst = supplierDAO.retrieveSupplierBasicInfo(user.getOrgId(), name);
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_SUPPLIER_LIST, lst);
		return rlt;
	}
	@Override
	public ResultContext retrieveMaterials(RequestContext rqs) {
		Integer supplierId = (Integer) rqs.getParameter(PurchaseTokens.KEY_SUPPLIER_ID);
		String activeInd = (String) rqs.getParameter(Tokens.KEY_ACTIVE_INDICATOR);
		logger.debug("retrieve materials for supplier id = " + supplierId);
		List<MaterialDTO> lst = materialDAO.retrieveMaterials(supplierId,activeInd);
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_MATERIAL_LIST, lst);
		return rlt;
	}
	@Override
	public ResultContext saveMaterial(RequestContext rqs) throws BaseException {
		UserDTO user = rqs.getUser();
		MaterialDTO material = (MaterialDTO) rqs.getParameter(PurchaseTokens.KEY_MATERIAL_DTO);
		material.setOrgId(user.getOrgId());
		if(material.getId() < 1){
			//New 
			boolean exist = materialDAO.hasMaterial(material.getSupplierId(), material.getCode(), material.getName(), null);
			if(exist)
				throw new DuplicateKeyException(StringUtils.join(new String[]{material.getCode(), material.getName()}, " "));
			material = materialDAO.createMaterial(material);
			logger.debug("Material created: " + material.getName());
		}else{
			//Update
			boolean exist = materialDAO.hasMaterial(material.getSupplierId(), material.getCode(), material.getName(), material.getId());
			if(exist)
				throw new DuplicateKeyException(StringUtils.join(new String[]{material.getCode(), material.getName()}, " "));	
			material = materialDAO.updateMaterial(material);
			logger.debug("Material updated: " + material.getName());
		}
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_MATERIAL_DTO, material);
		return rlt;
	}
	@Override
	public ResultContext retrieveColorStyles(RequestContext rqs) {
		Integer materialId = (Integer) rqs.getParameter(PurchaseTokens.KEY_MATERIAL_ID);
		String activeInd = (String) rqs.getParameter(Tokens.KEY_ACTIVE_INDICATOR);
		logger.debug("retrieve colors for material id = " + materialId);
		List<ColorStyleDTO> lst = colorStyleDAO.retrieveColorStyles(materialId, activeInd);
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_COLOR_STYLE_LIST, lst);
		return rlt;
	}
	@Override
	public ResultContext saveColorStyle(RequestContext rqs)
			throws BaseException {
		UserDTO user = rqs.getUser();
		ColorStyleDTO color = (ColorStyleDTO) rqs.getParameter(PurchaseTokens.KEY_COLOR_STYLE_DTO);
		color.setOrgId(user.getOrgId());
		if(color.getId() < 1){
			//New 
			boolean exist = colorStyleDAO.hasColorStyle(color.getMaterialId(), color.getCode(), color.getName(), null);
			if(exist)
				throw new DuplicateKeyException(StringUtils.join(new String[]{ color.getCode(), color.getName()}, " "));
			color = colorStyleDAO.createColorStyle(color);
			logger.debug("Color style created: " + color.getName());
		}else{
			//Update
			boolean exist = colorStyleDAO.hasColorStyle(color.getMaterialId(), color.getCode(), color.getName(), color.getId());
			if(exist)
				throw new DuplicateKeyException(StringUtils.join(new String[]{ color.getCode(), color.getName()}, " "));
			color = colorStyleDAO.updateColorStyle(color);
			logger.debug("Color style updated: " + color.getName());
		}
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_COLOR_STYLE_DTO	, color);
		return rlt;
	}
	@Override
	public ResultContext retrievePagedInquiryTasks(RequestContext rqs) {
		UserDTO user = rqs.getUser();
		String styleCode = (String) rqs.getParameter(DesignTokens.KEY_STYLE_CODE);
		String state = (String) rqs.getParameter(Tokens.KEY_STATE);
		Integer pageNo = (Integer) rqs.getParameter(Tokens.KEY_PAGE_NO);
		Integer pageSize = (Integer) rqs.getParameter(Tokens.KEY_PAGE_SIZE);
		List<InquiryTaskDTO> lst = inquiryTaskDAO.retrievePagedInquiryTasks(user.getOrgId(), styleCode, state, pageNo, pageSize);

		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_INQUIRY_TASK_LIST, lst);
		return rlt;
	}
	@Override
	public ResultContext retrieveInquiryTaskCount(RequestContext rqs) {
		UserDTO user = rqs.getUser();
		String styleCode = (String) rqs.getParameter(DesignTokens.KEY_STYLE_CODE);
		String state = (String) rqs.getParameter(Tokens.KEY_STATE);
		Integer rowCount = inquiryTaskDAO.retrieveInquiryTaskCount(user.getOrgId(), styleCode, state);
		ResultContext rlt = new ResultContext();
		rlt.addResult(Tokens.KEY_RECORD_COUNT, rowCount);
		return rlt;
	}
	@Override
	public ResultContext retrieveInquiryItems(RequestContext rqs) {
		UserDTO user = rqs.getUser();
		Integer taskId = (Integer) rqs.getParameter(PurchaseTokens.KEY_INQUIRY_TASK_ID);
		List lst = inquiryItemDAO.retrieveInquiryItems(taskId);
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_INQUIRY_ITEM_LIST, lst);
		return rlt;
	}
	@Override
	public ResultContext saveInquiryItem(RequestContext rqs) throws NoRecordUpdateException {
		UserDTO user = rqs.getUser();
		InquiryItemDTO item = (InquiryItemDTO) rqs.getParameter(PurchaseTokens.KEY_INQUIRY_ITEM_DTO);
		inquiryItemDAO.updateInquiryItem(item);
		//还原原料及颜色的值传回去，以免前台再重新取一次
		item.setMaterial(materialDAO.retrieveMaterial(item.getMaterial().getId()));
		item.setMaterialColor(colorStyleDAO.retrieveColorStyle(item.getMaterialColor().getId()));
		//If all items complete, update the task to CLOSE
		inquiryTaskDAO.updateInquiryTaskState(item.getTaskId());
		ResultContext rlt = new ResultContext();
		rlt.addResult(PurchaseTokens.KEY_INQUIRY_ITEM_DTO, item);
		return rlt;
	}
	@Override
	public ResultContext saveInquiryTask(RequestContext rqs)
			throws BaseException {
		InquiryTaskDTO task = (InquiryTaskDTO) rqs.getParameter(PurchaseTokens.KEY_INQUIRY_TASK_DTO);
		inquiryTaskDAO.updateInquiryTask(task);
		ResultContext rlt = new ResultContext();
		return rlt;
	}




}
